//
//  CustomTabBar.m
//  NotepadApp
//
//  Created by yobet on 2018/4/12.
//  Copyright © 2018年 HJ. All rights reserved.
//

#import "CustomTabBar.h"
@interface CustomTabBar ()
/**
 *  选中的按钮
 */
@property (nonatomic, weak) UIButton *selButton;

/** bigButton */
@property (nonatomic, weak) UIButton *bigButton;

/** 需要选中第几个 */
@property (nonatomic, assign) NSUInteger currentSelectedIndex;

@end
/** tabBarTag */
static NSInteger const BXTabBarTag = 12000;

@implementation CustomTabBar

- (void)setItems:(NSArray *)items {
    _items = items;
    for (int i = 0; i < items.count; i++) {
        UITabBarItem *item = items[i];
        if (i == 2) {
            UIButton *btn = [self configButtonWithItems:item];
            btn.tag = self.subviews.count + BXTabBarTag;
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
            [self addSubview:btn];
            self.bigButton = btn;
        } else {
            TabBarButton *btn = [TabBarButton buttonWithType:UIButtonTypeCustom];
            btn.item = item;
            btn.tag = self.subviews.count + BXTabBarTag;
            [btn setImage:item.image forState:UIControlStateNormal];
            [btn setImage:item.selectedImage forState:UIControlStateSelected];
            btn.adjustsImageWhenHighlighted = NO;
            [btn setTitle:item.title forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithHex:0xcccccc] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithHex:0xff4b64] forState:UIControlStateSelected];
            [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
            
            [self addSubview:btn];
            NSInteger subViewsCount = 1;
            if (self.seletedIndex) {
                subViewsCount = self.seletedIndex + 1;
            }
            if (self.subviews.count == subViewsCount) {
                self.currentSelectedIndex = self.subviews.count - 1;
                [self btnClick:btn];// 默认选中第一个
            }
            // 添加观察者
            [item addObserver:self forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:(__bridge void * _Nullable)(btn)];
        }
    }
}

- (void)dealloc {
    for (int i=0; i<self.items.count; i++) {
        if (i != 2) {
            [self.items[i] removeObserver:self forKeyPath:@"badgeValue"];
        }
    }
}
-(void)setSeleIndex:(BOOL)seleIndex {
    UIButton * btn = [self viewWithTag:BXTabBarTag];
    if (seleIndex) {
        [btn setTitleColor:[UIColor colorWithHex:0xff4b64] forState:UIControlStateSelected];
        [btn setImage:setImage(@"shouye1") forState:UIControlStateSelected];
    }else {
        [btn setTitleColor:[UIColor colorWithHex:0xffffff] forState:UIControlStateSelected];
        [btn setImage:setImage(@"shoye_yujian") forState:UIControlStateSelected];
    }
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    TabBarButton *btn = (__bridge TabBarButton *)(context);
    UITabBarItem *item = object;
    btn.item = item;
}

-(UIButton * )configButtonWithItems:(UITabBarItem *)item {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = self.subviews.count + BXTabBarTag;
    [btn setImage:item.image forState:UIControlStateNormal];
    [btn setImage:item.selectedImage forState:UIControlStateSelected];
    btn.adjustsImageWhenHighlighted = NO;
    [btn setTitle:item.title forState:UIControlStateNormal];
    return btn;
}

- (void)setDelegate:(id<CustomTabBarDelegate>)delegate{
    _delegate = delegate;
    [self btnClick:(TabBarButton *)[self viewWithTag:self.currentSelectedIndex + BXTabBarTag]];
}


- (void)btnClick:(UIButton *)button {
    _selButton.selected = NO;
    _selButton = button;
    if ([_delegate respondsToSelector:@selector(tabBar:didClickBtn:btn:)]) {
        [_delegate tabBar:self didClickBtn:button.tag - BXTabBarTag btn:button];
    }
}

/**
 *  外界设置索引页跟着跳转
 */
- (void)setSeletedIndex:(NSInteger)seletedIndex {
    _seletedIndex = seletedIndex;
    UIButton *button = [self viewWithTag:(BXTabBarTag + seletedIndex)];
    [self btnClick:button];
}


- (void)layoutSubviews {
    [super layoutSubviews];
    
    NSUInteger count = self.subviews.count;
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat w = [UIScreen mainScreen].bounds.size.width / count;
    CGFloat h = 49;
    for (int i = 0; i < count; i++) {
        UIButton *btn = self.subviews[i];
        x = i * w;
        if (i == 2) {
            y = -12;
            h += 12;
        }
        btn.frame = CGRectMake(x, y, w, h);
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat pointW = 43;
    CGFloat pointH = 61;
    CGFloat pointX = (SCREEN_WIDTH - pointW) / 2;
    CGFloat pointY = -12;
    CGRect rect = CGRectMake(pointX, pointY, pointW, pointH);
    if (CGRectContainsPoint(rect, point)) {
        return self.bigButton;
    }
    return [super hitTest:point withEvent:event];
}

@end


@interface TabBarButton ()
/**
 *  提醒数字
 */
@property (strong, nonatomic) BXBadgeView *badgeView;
@end

@implementation TabBarButton
/**
 *  小红点
 */
- (BXBadgeView *)badgeView {
    if (!_badgeView) {
        BXBadgeView *badgeView = [[BXBadgeView alloc] init];
        [self addSubview:badgeView];
        self.badgeView = badgeView;
    }
    return _badgeView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // 1.设置字体
        self.titleLabel.font = [UIFont systemFontOfSize:10];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.adjustsImageWhenHighlighted = NO;
        // 2.图片的内容模式
        self.imageView.contentMode = UIViewContentModeCenter;
    }
    return self;
}

- (void)setItem:(UITabBarItem *)item {
    _item = item;
    self.badgeView.badgeValue = item.badgeValue;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    // 文字位置
    self.titleLabel.left = 0;
    self.titleLabel.width = self.width;
    self.titleLabel.height = 16;
    if (@available(iOS 11.0, *)) {
        self.titleLabel.height -= 1;
    }
    self.titleLabel.top = self.height - self.titleLabel.height;
    self.imageView.width = self.currentImage.size.width;
    self.imageView.height = self.currentImage.size.height;
    self.imageView.left = (self.width - self.imageView.width) / 2;
    self.imageView.top = self.titleLabel.top - self.imageView.height - 4;
    // 小红点位置
    self.badgeView.left = CGRectGetMaxX(self.imageView.frame)-5;
    self.badgeView.top = 12;
    self.badgeView.width = 16;
    
}

- (void)setHighlighted:(BOOL)highlighted {
    
}

@end

@implementation BXBadgeView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.height = 16;
        self.userInteractionEnabled = NO;
        self.titleLabel.font = [UIFont systemFontOfSize:10];
        self.layer.cornerRadius = 8;
        self.layer.masksToBounds = YES;
        [self setBackgroundImage:[CommonTools imageCreateWithColor:[UIColor colorWithHex:0xfe6a7f]] forState:UIControlStateNormal];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        // 按钮的高度就是背景图片的高度
//        self.height = self.currentBackgroundImage.size.height;
    }
    return self;
}


#warning 需要修改红点尺寸位置在这里修改
- (void)setBadgeValue:(NSString *)badgeValue
{
    _badgeValue = [badgeValue copy];
    
    self.hidden = NO;
    if ([badgeValue integerValue] > 99) {
        badgeValue = @"...";
    } else if ([badgeValue integerValue] <= 0) {
        badgeValue = nil;
        self.hidden = YES;
    }
    // 设置文字
    [self setTitle:badgeValue forState:UIControlStateNormal];
    
    // 根据文字计算自己的尺寸
    CGFloat bgW = self.currentBackgroundImage.size.width;
    
    self.width = bgW;
    if (badgeValue.length > 1) {
        self.width = 26;
    }
}

@end
